import { HTTP } from '../util/http.js'

class ClassicModel extends HTTP {

  constructor() {
    super()
  }

  getLatest(sCallback) {
    this.request({
      url: 'classic/latest',
      success: (res) => {
        let resData = res.art
        sCallback(resData)
        this._setLatestIndex(resData.index)
        let key = this._getKey(resData.index)
        wx.setStorageSync(key, resData)
      }
    })
  }

  getMyFavor(success) {
    let params = {
      url: 'classic/favor',
      success: success
    }
    this.request(params)
  }

  getClassic(index,  nextOrPrevious, sCallback) {
    // 使用缓存，提升性能
    let key = nextOrPrevious == 'next' ? 
      this._getKey(index + 1) : this._getKey(index - 1)
    let classic = wx.getStorageSync(key)
    // console.log(classic)
    if (!classic) {
      this.request({
        url: 'classic/' + index + '/' + nextOrPrevious,
        success: (res) => {
          let resData = res.art
          // console.log('getClassic', resData)
          wx.setStorageSync(
            this._getKey(resData.index),
            resData.data
          )
          sCallback(resData)
        }
      })
    } else {
      sCallback(classic)
    }
  }

  isFirst(index){
    return index === 1 ? true : false
  }

  isLatest(index) {
    let latestIndex = this._getLatestIndex()
    return latestIndex == index ? true : false
  }

  _setLatestIndex(index) {
    wx.setStorageSync('latest', index)
  }

  _getLatestIndex() {
    let index = wx.getStorageSync('latest')
    return index
  }

  _getKey(index) {
    let key = 'classic-' + index
    return key
  }
}

export { ClassicModel }